﻿#region 命名空间

using System.Data.Entity;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;
using System.Linq;
using Sharp.Domain.CMSBoundedContext.Migrations;
using Sharp.Infrastructure;

#endregion

namespace Sharp.Domain.CMSBoundedContext
{
    /// <summary>
    ///     平台数据访问上下文。
    /// </summary>
    public partial class Entities : DbContext
    {
        private readonly PluralizationService _service = PluralizationService.CreateService(new CultureInfo("en-US"));
        #region 构造函数

        static Entities()
        {
#if DEBUG
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<Entities, Configuration>());
#endif
        }

        /// <summary>
        ///     构造函数，初始化一个新的<c>HospitalDbContext</c>实例。
        /// </summary>
        public Entities()
            : base("Entities")
        {
            //Configuration.AutoDetectChangesEnabled = true;
            //Configuration.ProxyCreationEnabled = false;
            //Configuration.LazyLoadingEnabled = false;
            Configuration.UseDatabaseNullSemantics = true;
        }

        #endregion


        #region OnModelCreating

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            #region 公约

            modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 4));
            modelBuilder.Properties<string>().Configure(x => x.HasMaxLength(50).IsUnicode(true));
            modelBuilder.Properties().Where(x => x.Name == "Id").Configure(x => x.HasColumnOrder(0));
            modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType<NonUnicodeAttribute>().Any()).Configure(c => c.IsUnicode(false));
            modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType<IsMaxLengthAttribute>().Any()).Configure(c => c.IsMaxLength());

            #endregion

            modelBuilder.Types().Configure(entity =>
            {
                entity.ToTable("CMS_" + _service.Pluralize(entity.ClrType.Name));
            });

            modelBuilder.Configurations.AddFromAssembly(typeof(Entities).Assembly);
        }

        #endregion
    }
}